package app.auto.runner.base;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.aliang.auto.R;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import app.auto.AndroidInstance;
import app.auto.runner.base.framework.CrashHandler;
import app.auto.runner.base.intf.FunCallback;
import app.auto.runner.base.intf.ListBuilder;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.intf.json.JsonToMapUtils;
import app.auto.runner.base.intf.json.JsonUtil;
import app.auto.runner.base.utility.ShareAlert;
import app.auto.runner.base.utility.ToastUtil;
import app.auto.runner.base.widget.DatePicker;
import base.recycleview.RecycleViewUtil;

import static android.content.Context.CLIPBOARD_SERVICE;

public class JsonPop extends AndroidInstance {

    public static final String RESTARTAPP = "restartapp";
    private boolean editableDirect;

    public static abstract class DatafetchImpl extends FunCallback {

        public abstract void dataIneractInit(FunCallback bombRecvFuncBack);

        public abstract void dataFetchImpl(Map params);

    }

    private boolean initExpand = true;
    private ListView lsv;
    private FunCallback bombRecvFuncBack;
    private DatafetchImpl datafetchImpl;
    private String interfacetitle;
    private String json_back_pop_confirm;


    FunCallback upload = null;

    public JsonPop setUploadFn(FunCallback upload) {
        this.upload = upload;
        return this;
    }

    public JsonPop setInitExpand(boolean initExpand) {
        this.initExpand = initExpand;
        return this;
    }

    public static JsonPop get(Context ctx) {
        return JsonPop.get(JsonPop.class, ctx);
    }

    Object currPathData = new ArrayList();
    String jsonContent;
    Object o;


    public AlertDialog d;

    public AlertDialog getD() {
        return d;
    }

    private BaseAdapter baseadapter;

    public Stack stack = new Stack();
    private long mExitTime;

    View iew;

    public boolean hideField;
    private Dialog typeD;
    private MapBuilder intentmap;

    public JsonPop setIntentmap(MapBuilder intentmap) {
        this.intentmap = intentmap;
        return this;
    }

    public void setHideField(boolean hideField) {
        this.hideField = hideField;
    }

    public boolean isHideField() {
        return hideField;
    }

    public boolean editStat;

    public void setEditStat(boolean editStat) {
        this.editStat = editStat;
    }

    public boolean isEditStat() {
        return editStat;
    }

    public Object title = "";

    Map titleMap;

    public JsonPop setTitleMap(Map titleMap) {
        this.titleMap = titleMap;
        this.title = transferTitledMap(titleMap);
        return this;
    }

    public JsonPop setTitle(Object title) {
        this.title = title;
        if (title instanceof Map) {
            Object object = title;
            this.titleMap = (Map) object;
            object = transferTitledMap(object);
            this.title = object;
        }
        return this;
    }

    private Object transferTitledMap(Object object) {
        if (object instanceof Map) {
            object = JsonToMapUtils.mapToJson((Map) object);
        }
        object = TextUtils.isEmpty((CharSequence) object) || object.toString().length() < 3 ? "" : object.toString().substring(1, object.toString().length() - 1);

        object = object.toString().replaceAll(" ", "").replaceAll("=", " = ").replaceAll(",", "\n");
        return object;
    }


    public Object getTitle() {
        return title;
    }


    public JsonPop prepare() {

        datafetchImpl.dataIneractInit(getRecvFuncBack());

        return this;
    }


    public JsonPop setInterfaceTitle(String title) {
        this.interfacetitle = title;

        return this;
    }


    public JsonPop pop(final Object json) {
//        ShareAlert.shareAlert((Activity) getContext(),json.toString());
        CrashHandler.getInstance().init(getContext());
        if (iew != null && iew.getParent() != null) {
            if (o != null) {

            } else
                ((ViewGroup) iew.getParent()).removeView(iew);
        }

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                iew = privateGetView(json.toString());

                iew.findViewById(R.id.left_title).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        d.dismiss();
                        d.cancel();
                        d = null;
                    }
                });
                iew.findViewById(R.id.settings).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        String table = (String) SPrefUtil.getValue("table");

                        ShareAlert.get(ShareAlert.class, v.getContext()).listAlert(Arrays.asList(new String[]{"切换  ( " + table + " )"}), new FunCallback() {
                            @Override
                            public void onCallback(Object result, Object object) {
                                super.onCallback(result, object);
                                if (result.toString().contains("切换")) {
                                    Dialog d = (Dialog) getParam();
                                    d.dismiss();
                                    d.cancel();
                                    BroadcastBuilder.build().sendAction("reinit", getContext(), MapBuilder.build(), BroadcastBuilder.Starttype.broadcast);
                                }
                            }
                        });
                    }
                });

                if (!TextUtils.isEmpty(interfacetitle)) {
                    ((TextView) iew.findViewById(R.id.interfacetitle)).setText(interfacetitle);
                }

                if (TextUtils.isEmpty((CharSequence) title)) {
                    iew.findViewById(R.id.createfile).setVisibility(View.GONE);
                } else if (title instanceof String) {
                    iew.findViewById(R.id.createfile).setVisibility(View.VISIBLE);
                    ((TextView) iew.findViewById(R.id.createfile)).setText((String) title);
                    BroadcastBuilder.build().receive(JSON_POP_CONFIRM, "", getContext(), new FunCallback() {
                        @Override
                        public void onCallback(Object result, Object object) {
                            super.onCallback(result, object);
                            Map m = (Map) ((Intent) object).getSerializableExtra("params");
                            try {
                                title = setTitleMap(m).title;
//                                ShareAlert.shareAlert((Activity) result, m.toString()
//                                        + "\n\n"
//                                        + title);

                                if (datafetchImpl != null) {
                                    datafetchImpl.dataFetchImpl(titleMap);
                                }
                                new Handler(Looper.getMainLooper(), new Handler.Callback() {

                                    @Override
                                    public boolean handleMessage(@NonNull Message msg) {
                                        ((TextView) iew.findViewById(R.id.createfile)).setText((String) title);
                                        return false;
                                    }
                                }).sendEmptyMessage(0);
                            } catch (Exception e) {
                                CrashHandler.errorDialog(e);

                            }
                        }
                    });
                    iew.findViewById(R.id.createfile).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            JsonPop jsonpop = JsonPop.get(JsonPop.class, v.getContext()).setEditableDirect(true).setBackToken(JSON_POP_CONFIRM).setEditableDirect(true).setInterfaceTitle(getContext().getString(R.string.interfacetitle_params)).pop(JsonToMapUtils.mapToJson(titleMap));


//                            jsonpop.lsv.addFooterView(TextViewBuilder.get(TextViewBuilder.class, getContext()).setHeight(-2).setWidth(-1).setText("+").setGravity(Gravity.CENTER).setSizeValue(DipUtil.fromDip(17)).setOnClick(new FunCallback() {
//                                @Override
//                                public void onCallback(Object result, Object object) {
//                                    super.onCallback(result, object);
//
//                                }
//                            }).get());

                        }
                    });
                } else {

                    addRecycleView(iew.findViewById(R.id.recycleview), title);
                }
                if (d != null) {
                    return;
//                    d.dismiss();
//                    d.cancel();
//                    d = null;
                }
                d = (AlertDialog) DialogUtil.showDialog(getContext(), iew, "退出", new DialogUtil.DialogClicker() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        ((ViewGroup) iew.getParent()).removeView(iew);
                        super.onClick(dialog, arg1);
                        BroadcastBuilder.remove("<number/>", getContext());
//                        DialogUtil.cancelDialog();
                    }
                }, "字段", null, "编辑", null);

                d.getButton(DialogInterface.BUTTON_POSITIVE).setText("字段");
                d.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (!((TextView) v).getText().toString().equals("线性")) {
                            ((TextView) v).setText("线性");
                        } else {
                            ((TextView) v).setText("字段");
                        }
                        setHideField(!isHideField());
                        notifyListView();
                    }
                });
                d.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShareAlert.get(ShareAlert.class, getContext()).listAlert(Arrays.asList(new String[]{"分享"}), new FunCallback() {
                            @Override
                            public void onCallback(Object result1, Object object) {
                                super.onCallback(result1, object);
                                String title = "";
                                if (iew.findViewById(R.id.interfacetitle) == null) {

                                } else {
                                    title = ((TextView) iew.findViewById(R.id.interfacetitle)).getText().toString();
                                    if (title != null) {
                                        title = title.trim();
                                    }
                                    title = TextUtils.isEmpty(title) ? "" : "【" + title + "】";
                                }
                                String sharejson = json.toString();
                                if (sharejson.startsWith("[")) {
                                    List lt = JsonToMapUtils.jsontoList(sharejson);
                                    if (lt.size() > 2) {
                                        lt = lt.subList(0, 2);
                                        sharejson = JsonToMapUtils.listtoJson(lt);
                                    }
                                }

                                ShareUtil.get(ShareUtil.class, getContext()).shareMsg("", "", (title.isEmpty() ? "" : title + "\n\n") + "请求：" + "\n" + getTitle().toString() + "\n\n" + "结果：" + "\n" + sharejson.toString(), "");
                                ((Dialog) getParam()).dismiss();
                                ((Dialog) getParam()).cancel();
                            }
                        });
                    }
                });
                d.setCancelable(false);
                d.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                            MapBuilder mb = MapBuilder.build();
                            String json = "";
                            if (currPathData instanceof List) {
                                json = JsonToMapUtils.listtoJson((List) currPathData);
                            } else if (currPathData instanceof Map) {
                                json = JsonToMapUtils.mapToJson((Map) currPathData);
                            }
                            if (!TextUtils.isEmpty(json) && JsonUtil.isJSONObject(json.toString())) {
                                mb.withMap(JsonToMapUtils.parseJsonToMap(json.toString()));
                            }
                            if (!TextUtils.isEmpty(json_back_pop_confirm)) {
                                BroadcastBuilder.build().sendAction(json_back_pop_confirm, getContext(), MapBuilder.build().withMap(mb.get()), BroadcastBuilder.Starttype.broadcast);
                            }
                            onBackPressed(null);
                        }
                        return true;
                    }
                });
                d.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        BroadcastBuilder.remove(JSON_POP_CONFIRM, getContext());
                        BroadcastBuilder.remove(RESTARTAPP, getContext());

                    }
                });
                d.show();
//                KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_BACK, scanCode=158, metaState=0, flags=0x8, repeatCount=0, eventTime=79524767, downTime=79524767, deviceId=0, source=0x101 }
//                KeyEvent { action=ACTION_UP, keyCode=KEYCODE_BACK, scanCode=158, metaState=0, flags=0x28, repeatCount=0, eventTime=79529813, downTime=79524767, deviceId=0, source=0x101 }


            }
        });
        return this;
    }

    private Activity getActivity() {
        return (Activity) getContext();
    }

    private JsonPop setEditableDirect(boolean b) {
        this.editableDirect = b;
        return this;
    }

    private JsonPop setBackToken(String json_pop_confirm) {
        this.json_back_pop_confirm = json_pop_confirm;
        return this;
    }

    public String JSON_POP_CONFIRM = "json_pop_confirm" + System.currentTimeMillis();

    protected void addRecycleView(View viewById, Object title) {
        ListBuilder listBuilder = ListBuilder.build();
        if (title instanceof Map) {

            for (Object e : ((Map) title).entrySet()) {
                Object k = ((Map.Entry) e).getKey();
                Object v = ((Map.Entry) e).getValue();
                listBuilder = listBuilder.newMapBuilder().add("txt", k + "=" + v).getListHolder();

            }
            viewById.setVisibility(View.VISIBLE);
            RecycleViewUtil.get(RecycleViewUtil.class, getContext()).setRecyclerView((RecyclerView) viewById).setData(listBuilder.get()).get();
        }

    }


    public Object getItemOfAdapter() {
        return currPathData;
    }

    public List currNodeOfList;

    public View getView(String json) {
        return privateGetView(json);
    }


    private View privateGetView(String json) {
        if (iew != null) {
            o = JsonUtil.extractJsonRightValue(json);
            last = null;
            stack.clear();
            pushCurr(o);

            for (int i = 0; i < lsv.getHeaderViewsCount(); i++) {
                lsv.removeHeaderView(lsv.getChildAt(i));
            }

            return iew;
        }
        View view = LayoutInflater.from(getContext()).inflate(R.layout.instance_activity_json, null);
        if (json == null) {
            return null;
        }
        view.findViewById(R.id.right).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                setHideField(!isHideField());
                if (isHideField()) {
                    ((TextView) v).setText("线性");
                } else {
                    ((TextView) v).setText("字段");
                }
                notifyListView();
            }
        });
        view.findViewById(R.id.left).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                setEditStat(!isEditStat());
                if (isEditStat()) {
                    ((TextView) v).setText("编辑");
                } else {
                    ((TextView) v).setText("显示");
                }
                notifyListView();
            }
        });

        o = JsonUtil.extractJsonRightValue(json);

        lsv = ((ListView) view.findViewById(R.id.listview));
        lsv.setAdapter(baseadapter = new BaseAdapter() {

            Set<Integer> expand = new TreeSet<Integer>();

            @Override
            public int getCount() {
                if (currPathData instanceof Map) {
                    return ((Map) currPathData).size();
                } else if (currPathData instanceof List) {
                    return ((List) currPathData).size();
                }
                return 0;
            }


            @Override
            public Object getItem(int position) {
                if (currPathData instanceof Map) {
                    return (currNodeOfList = new ArrayList<Map.Entry>(((Map) currPathData).entrySet())).get(position);
                } else if (currPathData instanceof List) {
                    return ((List) currPathData).get(position);
                }
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(final int position, View convertView, final ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.instance_auto_string_json_item, null);
                }
                if (isHideField()) {
                    ((TextView) convertView.findViewById(R.id.desc)).setVisibility(View.GONE);
                } else {
                    ((TextView) convertView.findViewById(R.id.desc)).setVisibility(View.VISIBLE);
                }
                final Object value;
                final Object entrykey;

                //currDataPath = map
                if (getItem(position) instanceof Map.Entry) {
                    //键值   123: {}
                    value = ((Map.Entry) getItem(position)).getValue();
                    entrykey = ((Map.Entry) getItem(position)).getKey();

                    ((TextView) convertView.findViewById(R.id.desc)).setText("      " + ((Map.Entry) getItem(position)).getKey() + "    ：");

                    String textshow = "";
                    if (value instanceof Map || value instanceof List) {
                        final View finalConvertView1 = convertView;
                        convertView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pushCurr(((Map.Entry) getItem(position)).getValue());
                                navPush(lsv, ((TextView) finalConvertView1.findViewById(R.id.desc)).getText().toString(), ((TextView) finalConvertView1.findViewById(R.id.name)).getText().toString());

                            }
                        });
                        if (value instanceof List) {

                            textshow = "[ " + /*((List) value).size() */"" + " ]";
                        } else if (value instanceof Map) {
                            textshow = "{ " + /*((Map) value).size()*/"" + " }";

                        }
                        convertView.findViewById(R.id.name).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                pushCurr(value);
                                navPush(lsv, ((TextView) finalConvertView1.findViewById(R.id.desc)).getText().toString(),
                                        ((TextView) finalConvertView1.findViewById(R.id.name)).getText().toString());
                            }
                        });
                        final View finalConvertView4 = convertView;
                        convertView.findViewById(R.id.desc).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    ShareAlert.get(ShareAlert.class, getContext()).shareEdit(false, ((TextView) finalConvertView4.findViewById(R.id.desc)).getText().toString().replace("：", "").trim(), "", new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, Object object) {
                                            super.onCallback(result, object);

//                                        currNodeOfList.remove(((Map.Entry) getItem(position)));
//                                        currNodeOfList.add(((Map.Entry) getItem(position)));
//                                        Map m = ((Map) getItemOfAdapter());
//                                        m.remove((((EditText) object).getText().toString()));

//                                        ((Map.Entry) getItem(position)).
//                                        (((EditText) object).getText().toString());
                                            baseadapter.notifyDataSetChanged();
                                        }
                                    }, "删除", new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, Object object) {
                                            super.onCallback(result, object);
                                            Map m = ((Map) getItemOfAdapter());
                                            m.remove((((EditText) object).getText().toString()));
                                            baseadapter.notifyDataSetChanged();
//                                        clipText(((EditText) ((Dialog) result).findViewById(123)).getText().toString());
                                        }
                                    });
                                } catch (Exception e) {
                                    CrashHandler.errorDialog(e);
                                }
//                                pushCurr(value);
//                                navPush(lsv, ((TextView) finalConvertView1.findViewById(R.id.desc)).getText().toString(),
//                                        ((TextView) finalConvertView1.findViewById(R.id.name)).getText().toString());

                            }
                        });

                    } else {
                        final View finalConvertView = convertView;
                        textshow = "" + value == null ? "" : value + "";
                        final String finalTextshow = textshow;
                        if (initExpand) {

                            expand.add(position);
                        }
                        final String finalTextshow1 = textshow;
//                        if(getItem(position) instanceof Map) {


                        convertView.findViewById(R.id.name).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                                if (isEditStat()) {
//                                    //图片
//                                    //文字
//                                    //
//
//                                    popedit(position);
//                                } else {
//                                    expandRightForm(position);
//                                }


                                try {
//                                    ShareAlert.shareAlert((Activity) getContext(), (String) (getItem(position)).toString());
//                                    if(true){
//                                        return;
//                                    }
                                    ShareAlert.get(ShareAlert.class, getContext()).setEditableDirected(editableDirect).setDoSelect(new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, final Object object) {
                                            super.onCallback(result, object);
                                            final String txt = (String) result;
                                            final EditText et = (EditText) object;
                                            if (result.toString().equals("整型")) {

                                            } else if (result.toString().equals("浮点")) {

                                            } else if (result.toString().equals("上传")) {
                                                new Handler(Looper.getMainLooper(), new Handler.Callback() {
                                                    @Override
                                                    public boolean handleMessage(@NonNull Message msg) {
                                                        BroadcastBuilder.build().receive("upload", "", getContext(), new FunCallback() {
                                                            @Override
                                                            public void onCallback(Object result, Object object) {
                                                                super.onCallback(result, object);
                                                                ((Map.Entry) getItem(position)).setValue(((TextView)et).getText().toString());
                                                                baseadapter.notifyDataSetChanged();
                                                                BroadcastBuilder.remove("upload",getActivity());
                                                            }
                                                        });
                                                        upload.onCallback(txt, et);

                                                        return false;
                                                    }
                                                }).sendEmptyMessage(0);
                                            } else if (result.toString().equals("日期")) {
                                                DatePicker.get(DatePicker.class, getContext()).pick(new FunCallback() {
                                                    @Override
                                                    public void onCallback(Object result, Object object) {
                                                        super.onCallback(result, object);
                                                        Date date = ((Date) result);
                                                        String rt = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                                        et.setText(rt);
                                                    }
                                                });
                                            }
                                        }
                                    }).shareEdit(false, value.toString(), "编辑", new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, Object object) {
                                            super.onCallback(result, object);

                                        }
                                    }, "复制", new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, Object object) {
                                            super.onCallback(result, object);
                                            clipText(((EditText) ((Dialog) result).findViewById(123)).getText().toString());
                                        }
                                    });
                                } catch (Exception e) {
                                    CrashHandler.errorDialog(e);
                                }
//                                popedit(position);

                            }


                        });

                        convertView.findViewById(R.id.desc).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    ShareAlert.get(ShareAlert.class, getContext()).shareEdit(false, (String) entrykey.toString(), "", new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, Object object) {
                                            super.onCallback(result, object);

//                                        currNodeOfList.remove(((Map.Entry) getItem(position)));
//                                        currNodeOfList.add(((Map.Entry) getItem(position)));
//                                        Map m = ((Map) getItemOfAdapter());
//                                        m.remove((((EditText) object).getText().toString()));

//                                        ((Map.Entry) getItem(position)).
//                                        (((EditText) object).getText().toString());
                                            baseadapter.notifyDataSetChanged();
                                        }
                                    }, "删除", new FunCallback() {
                                        @Override
                                        public void onCallback(Object result, Object object) {
                                            super.onCallback(result, object);
                                            Map m = ((Map) getItemOfAdapter());
                                            m.remove((((EditText) object).getText().toString()));
                                            baseadapter.notifyDataSetChanged();
//                                        clipText(((EditText) ((Dialog) result).findViewById(123)).getText().toString());
                                        }
                                    });
                                } catch (Exception e) {
                                    CrashHandler.errorDialog(e);
                                }
                            }
                        });
                        convertView.findViewById(R.id.desc).setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                v.setEnabled(false);
//                                if (isEditStat()) {
                                //1.图片     图片控件
                                //2.文字     输入
                                //3.日期     日期控件
                                //  数字
                                //4.富媒体
                                clipText(((TextView) v).getText().toString());
                                v.setEnabled(true);
//                                } else {
//                                    clipText(finalTextshow1);
//                                }


                                return false;
                            }
                        });
                        convertView.findViewById(R.id.name).setOnLongClickListener(new View.OnLongClickListener() {
                            @Override
                            public boolean onLongClick(View v) {
                                v.setEnabled(false);
//                                if (isEditStat()) {
                                //1.图片     图片控件
                                //2.文字     输入
                                //3.日期     日期控件
                                //  数字
                                //4.富媒体
                                clipText(((TextView) v).getText().toString());
                                v.setEnabled(true);
//                                } else {
//                                    clipText(finalTextshow1);
//                                }


                                return false;
                            }
                        });
                        convertView.setOnClickListener(null);
//                        }else{
//                            convertView.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//                                    expandRightForm(position);
//                                }
//                            });
//                        }

                    }

                    //复制 展示
                    //
                    textshow = TextUtils.isEmpty(textshow) ? "--" : textshow;
                    ((TextView) convertView.findViewById(R.id.name)).setText(textshow);

                } else {
                    final Object val = getItem(position);

                    final View finalConvertView2 = convertView;
                    final View finalConvertView3 = convertView;
                    getRightValue(position, convertView, val, new FunCallback() {
                        @Override
                        public void onCallback(Object result, Object object) {
                            super.onCallback(result, object);
                            pushCurr(val);
                            navPush(lsv, ((TextView) finalConvertView3.findViewById(R.id.desc)).getText().toString(),
                                    ((TextView) finalConvertView2.findViewById(R.id.name)).getText().toString());
                        }
                    });

                }
                if (expand.contains(position)) {

                    ((TextView) convertView.findViewById(R.id.name)).setMaxLines(100);
                    ((TextView) convertView.findViewById(R.id.name)).setSingleLine(false);

                } else {
                    ((TextView) convertView.findViewById(R.id.name)).setMaxLines(1);

                    ((TextView) convertView.findViewById(R.id.name)).setSingleLine(true);

                }
                ((TextView) convertView.findViewById(R.id.name)).invalidate();

                return convertView;
            }


            public void popedit(final int position) {
                typeD = DialogUtil.showDialog("", Arrays.asList(new String[]{"图片", "文字", "日期", "数字", "时间"}), getContext(), new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent2, View view, int position2, long id) {
                        String txt = (String) parent2.getItemAtPosition(position2);
                        FunCallback funcallbback = new FunCallback() {
                            @Override
                            public void simpleRun(Object aty, Object... p) {
                                super.simpleRun(aty, p);
                                ((Map) currPathData).put(((Map.Entry) getItem(position)).getKey(), aty);
                                baseadapter.notifyDataSetChanged();
                                typeD.dismiss();
                                typeD.cancel();
                            }
                        };
                        Map m = MapBuilder.build().get();
                        if (getItem(position) instanceof Map.Entry) {
                            String value = (String) ((Map.Entry) getItem(position)).getValue();
                            m = MapBuilder.build().add("value", value).get();
                        } else if (getItem(position) instanceof Map) {
                            m = (Map) getItem(position);
                        }

                        if (txt.equals("图片")) {
                            String key = Constant.control_image;
                            callbackset(key, m, funcallbback);
                        } else if (txt.equals("文字")) {
                            String key = Constant.control_txt;
                            callbackset(key, m, funcallbback);
                        } else if (txt.equals("日期")) {
                            String key = Constant.control_date;
                            callbackset(key, m, funcallbback);
                        } else if (txt.equals("数字")) {
                            String key = Constant.control_number;
                            callbackset(key, m, funcallbback);
                        } else if (txt.equals("时间")) {
                            String key = Constant.control_time;
                            callbackset(key, m, funcallbback);
                        }

                    }


                }, R.layout.title_listview);
                typeD.show();
            }

            public void expandRightForm(int position) {
                if (expand.contains(position)) {
                    expand.remove(position);
                } else {
                    expand.add(position);
                }
                notifyDataSetChanged();
            }


        });
        pushCurr(o);

        return view;
    }


    private void navPush(final ListView lsv, String desc, String name) {
        final View convertView;
        lsv.addHeaderView(convertView = LayoutInflater.from(getContext()).inflate(R.layout.instance_auto_string_json_item, null));
        if (isHideField()) {
            ((TextView) convertView.findViewById(R.id.desc)).setVisibility(View.GONE);
        } else {
            ((TextView) convertView.findViewById(R.id.desc)).setVisibility(View.VISIBLE);
        }

        ((TextView) convertView.findViewById(R.id.desc)).setText("•    " + desc.trim());
        ((TextView) convertView.findViewById(R.id.name)).setText(name);
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i;
                Object io = stack.get(i = lsv.indexOfChild(convertView));
                for (int j = stack.size() - 1; j > i; j--) {
                    onBackPressed(null);
                }

            }
        });
//
//            textshow = "> " + textshow;
//            //复制 展示
//            //
//            ((TextView) convertView.findViewById(R.id.name)).setText(textshow);
//        } else {
//            Object val = oo;
//            if (oo instanceof Map) {
//                value = ((Map) oo);
//
//            }
//            ((TextView) convertView.findViewById(R.id.desc)).setText(value + "    :");
//
//
//            getRightValue(0, convertView, val, new FunCallback() {
//                @Override
//                public void onCallback(Object result, Object object) {
//                    super.onCallback(result, object);
//                    pushCurr(oo);
//                }
//            });
//
//        }
        ((TextView) convertView.findViewById(R.id.name)).setMaxLines(1);
        ((TextView) convertView.findViewById(R.id.name)).invalidate();
        lsv.invalidate();
    }

    private void getRightValue(int position, final View convertView, final Object val, final FunCallback callback) {
        Object value = null;
        if (val instanceof Map) {
            value = val;

            ((TextView) convertView.findViewById(R.id.desc)).setText("      [ " + position + " ]    ->");

            ((TextView) convertView.findViewById(R.id.name)).setText("{ " + "" + " }" + "   "/*+((Map) value).size()*/);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onCallback(null, null);
                }
            });

            convertView.findViewById(R.id.name).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onCallback(null, null);
                }
            });
            convertView.findViewById(R.id.desc).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //del

                    callback.onCallback(null, null);
                }
            });
        } else if (val instanceof List) {

            value = val;

            ((TextView) convertView.findViewById(R.id.desc)).setText("      [" + position + "]     ->");

            ((TextView) convertView.findViewById(R.id.name)).setText("[     " + "" + " ]" + "   "/*+((List) value).size()*/);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onCallback(null, null);
                }
            });

            convertView.findViewById(R.id.name).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onCallback(null, null);
                }
            });
            convertView.findViewById(R.id.desc).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //del
//                    try {
//                        ShareAlert.get(ShareAlert.class, getContext()).shareEdit(false, (String) ((TextView)convertView.findViewById(R.id.desc)).getText().toString(), "", new FunCallback() {
//                            @Override
//                            public void onCallback(Object result, Object object) {
//                                super.onCallback(result, object);
//
////                                        currNodeOfList.remove(((Map.Entry) getItem(position)));
////                                        currNodeOfList.add(((Map.Entry) getItem(position)));
////                                        Map m = ((Map) getItemOfAdapter());
////                                        m.remove((((EditText) object).getText().toString()));
//
////                                        ((Map.Entry) getItem(position)).
////                                        (((EditText) object).getText().toString());
//                                baseadapter.notifyDataSetChanged();
//                            }
//                        }, "删除", new FunCallback() {
//                            @Override
//                            public void onCallback(Object result, Object object) {
//                                super.onCallback(result, object);
//                                Map m = ((Map) getItemOfAdapter());
//                                m.remove((((EditText) object).getText().toString()));
//                                baseadapter.notifyDataSetChanged();
////                                        clipText(((EditText) ((Dialog) result).findViewById(123)).getText().toString());
//                            }
//                        });
//                    } catch (Exception e) {
//                        CrashHandler.errorDialog(e);
//                    }
                    callback.onCallback(null, null);
                }
            });
        } else {
            ((TextView) convertView.findViewById(R.id.desc)).setText("      " + val.toString());
            final Object finalValue = value;
            convertView.findViewById(R.id.desc).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ShareAlert.shareAlert((Activity) v.getContext(), finalValue.toString());
                }
            });

            convertView.setOnClickListener(null);
        }
    }

    public void callbackset(String key, final Object item, final FunCallback funcallbback) {
        BroadcastBuilder.get(BroadcastBuilder.class, getContext()).setIntentMap(intentmap == null ? MapBuilder.build().get() : intentmap.get()).setDataItem(MapBuilder.build().withMap((Map) item).get()).broadcast(key, new FunCallback() {

            @Override
            public void onCallback(Object result, final Object object) {
                super.onCallback(result, object);

                String rt = "";
                Map params = (Map) ((Intent) object).getSerializableExtra("params");
                if (params != null && params instanceof Map) {
                    rt = (String) params.get("rt");
                    if (params != null && params.containsKey("isok")) {
                        funcallbback.setParam(rt);
                        setItemVal(funcallbback);
                    } else {

                    }
                }
//                else if(params instanceof String){
//
//                }

                BroadcastBuilder.remove(((Intent) object).getAction(), getContext());
                BroadcastBuilder.remove(((Intent) object).getAction().replace("back", "front"), getContext());

            }
        });
    }

    private void setItemVal(FunCallback funCallback) {
        funCallback.simpleRun(funCallback.getParam());

    }


    private void clipText(String finalTextshow1) {
        ClipboardManager myClipboard;
        myClipboard = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
        ClipData myClip;
        String text = finalTextshow1;
        myClip = ClipData.newPlainText("text", text);
        myClipboard.setPrimaryClip(myClip);
        ToastUtil.live((Activity) getContext()).toast("已复制");
    }

    private void notifyListView() {
        if (baseadapter != null) {
            baseadapter.notifyDataSetChanged();
        }
    }

    private void pushCurr(Object val) {
        if (stack.size() >= 1) {
            last = stack.peek();
        } else {
            last = o;
        }
        stack.push(val);
        currPathData = val;
        if (baseadapter != null) {
            baseadapter.notifyDataSetChanged();
        }


    }

    Object last;

    private int back() {
        if (stack.size() <= 1) {
            return 1;
        }

        currPathData = stack.elementAt(stack.size() - 2);
        stack.pop();
        baseadapter.notifyDataSetChanged();
        if (lsv.getHeaderViewsCount() > 0) {
            lsv.removeHeaderView(lsv.getChildAt(lsv.getHeaderViewsCount() - 1));
        }

        return stack.size();
    }

    public void onBackPressed(FunCallback exitFuncCallback) {
        if (stack.size() == 1) {
            if (exitFuncCallback == null) {
                d.cancel();
                d.dismiss();
            } else
                exitFuncCallback.simpleRun(null);
        } else {
            back();
        }
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        pop(mp.toString());
        return null;
    }


    public FunCallback getRecvFuncBack() {
        return bombRecvFuncBack;
    }


    public JsonPop setBombRecvFuncBack(FunCallback funCallback) {
        bombRecvFuncBack = funCallback;
        return this;
    }

    public JsonPop setDataFetchImpl(DatafetchImpl funCallback) {
        datafetchImpl = funCallback;
        return this;
    }


    String table;


    public JsonPop pop(String title, Map titleMap, String result) {
        privatePop(title, titleMap, result);
        return this;
    }

    private void privatePop(String title, Map titleMap, String result) {
        try {
            setTitle(title).setTitleMap(titleMap).pop(result);
        } catch (Exception e) {
            CrashHandler.getInstance().init(getActivity());
            CrashHandler.errorDialog(e);
        }
    }
}
